var entityCollection = require('../../../Base/server/controllers/EntityCollection'),
	routingController = require('./Routing.server.controller');

//根据根据工艺路线查找全部工序
exports.findOperations = function(routingId, completeFun){
	var entity = entityCollection.getEntity("Operation");
	entity.find({Routing: routingId}, {Sequence: 1}, {path: 'Work'}, function(err, records){
		if(err){
			var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询工序错误，请检查查询参数！';
            completeFun(newErr);
		}
		else{
			completeFun(null, records);
		}
	});
};

//根据工艺路线查找全部质检序
exports.findQCOperations = function(routingId, completeFun){
	this.findOperations(routingId, function(err, records){
		if(err){
            completeFun(err);
		}
		else{
			var qcOpperations = [];
			for(var i=0; i<records.length; i++){
				if (records[i].IsQCpoint) {
					qcOpperations.push(records[i]);
				};
			}
			completeFun(null, qcOpperations);
		}
	});
};

//根据工艺路线ID和作业ID查找工序
exports.findByRoutingAndWork = function(routingId, workId, completeFun){
	var entity = entityCollection.getEntity("Operation");
	entity.findOne({Routing: routingId, Work: workId}, {path: 'Work'}, function(err, record){
        if(err){
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工序错误';
            newErr.message = '根据工艺路线和作业，没有找到对应的工序！';
            completeFun(newErr);
        }
        else{
            completeFun(null, record);
        }
    });
};

//根据物料和作业查找工序
exports.findByItemMasterAndWork = function(itemMasterId, workId, completeFun){
	var self = this;
	routingController.findByItemMaster(itemMasterId, function(err, routingRecord){
		if(err){
            completeFun(err);
		}
		else{
			if (routingRecord == null) {
				var newErr = new Error();
	            newErr.leval = 9;
	            newErr.title = '查询工艺路线失败';
	            newErr.message = '该物料没有对应的工艺路线！';
	            completeFun(newErr);
	        }
	        else{
	        	self.findByRoutingAndWork(routingRecord._id, workId, function(err, operationRecord){
	        		completeFun(err, operationRecord);
	        	});
	        }
		}
	});
};